import os, flask, sqlite3, paramiko, logging

from link.sftpGetWindows import sftpGetWindows
from link.sftpLink import sftpLink
from tools.stopSSHServer import killApiOut
from thread.apiGoThread import apiGoThread
from tools.iuGetpp import iuGetpp
from tools.setHttpOrganization import after_request
from logging import handlers

api = flask.Flask(__name__)
api.after_request(after_request)

#打印日志
logger = logging.getLogger('')
rth = handlers.RotatingFileHandler("./log/serverMain.log",maxBytes=10*1024*1024,backupCount=7)
logger.setLevel(logging.INFO)
rth.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
logger.addHandler(rth)

@api.route('/main', methods=['post'])
def main():
    cmd = flask.request.values.get('cmd')

    # 启动ssh终端（接口没有返回信息，而且会阻塞）
    if cmd == 'start':
        apiport = flask.request.values.get('apiport')
        outport = flask.request.values.get('outport')
        ip = flask.request.values.get('ip')
        user = flask.request.values.get('user')
        name = flask.request.values.get('name')
        passwd,port = iuGetpp(ip,user,name)
        size = flask.request.values.get('size')
        timeout = flask.request.values.get('timeout')

        logger.info("cmd=" + cmd + ", ip=" + ip + ", user=" + user + ", sshport=" + port.__str__() + ", apiport=" + apiport + ", outport=" + outport + ", 终端进程启动中……")

        # 程序运行到这里就进入另一个进程中了，此模块的最后一句。
        # Process(target=startSSH(ip, port.__str__(), user, passwd, size, timeout, apiport, outport)).start()
        # 修改后可以正常返回状态
        thread2 = apiGoThread(ip, port.__str__(), user, passwd, size, timeout, apiport, outport)
        thread2.start()
        return "200"
    # 停止ssh终端
    elif cmd == 'stop':
        apiport = flask.request.values.get('apiport')
        outport = flask.request.values.get('outport')
        sshstatus = flask.request.values.get('sshstatus')

        res = killApiOut(apiport)
        killApiOut(outport)
        killApiOut(sshstatus)

        return res
    # 查询sshhost数据表
    elif cmd == 'selectSSH':
        conn = sqlite3.connect('../main/sqlite3/ssh.db')
        c = conn.cursor()
        result = c.execute("select * from ssh;")
        body = ""
        for row in result:
            name = row[1]
            ip = row[2]
            port = row[3]
            user = row[4]
            id = row[0]
            body = body + "<div id='" + ip + ":" + port.__str__() + ":" + user + ":" + name + ":" + id.__str__() + "' class='left-mother-list' onclick='shellNum(this)'  title='"+ ip +"("+ user +")' oncontextmenu='deleteHost(this);return false;'>" + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + name +  "</div>"
        conn.commit()
        conn.close()
        return body
    elif cmd == 'addhost':
        name = flask.request.values.get('name')
        ip = flask.request.values.get('ip')
        port = flask.request.values.get('port')
        user = flask.request.values.get('user')
        passwd = flask.request.values.get('passwd')
        conn = sqlite3.connect('../main/sqlite3/ssh.db')
        c = conn.cursor()
        c.execute("INSERT INTO ssh (NAME,IP,PORT,USER,PASSWD) \
              VALUES (" + "'" + name + "'" + "," + "'" + ip + "'" + "," + port + "," + "'" + user + "'" + "," + "'" + passwd + "'" + ")")
        conn.commit()
        conn.close()
    elif cmd == 'deletehost':
        deleteID = flask.request.values.get('deleteID')
        conn = sqlite3.connect('../main/sqlite3/ssh.db')
        c = conn.cursor()
        c.execute("delete from ssh where ID = " + deleteID + ";")
        conn.commit()
        conn.close()
    # elif cmd == 'openlog': # 打开日志文件夹
    #     start_directory = r'.\log'
    #     os.startfile(start_directory)
    elif cmd == 'sftpLink':
        # 传入IP、用户名、查看的目录
        ip = flask.request.values.get('ip')
        user = flask.request.values.get('user')
        dirList = flask.request.values.get('dirList')
        name = flask.request.values.get('name')
        passwd,port = iuGetpp(ip,user,name)

        dirlist = sftpLink(ip,port,user,passwd,dirList.__str__())

        return dirlist
    elif cmd == 'sftpGetWin':
        dirList = flask.request.values.get('dirList')
        thisList = sftpGetWindows(dirList)
        return thisList
    elif cmd == 'sftpDown':
        # 传入IP、用户名、下载的文件路径、下载到的路径
        ip = flask.request.values.get('ip')
        user = flask.request.values.get('user')
        file = flask.request.values.get('file')
        toFile = flask.request.values.get('toFile')
        name = flask.request.values.get('name')
        passwd,port = iuGetpp(ip,user,name)

        transport = paramiko.Transport((ip,int(port)))
        transport.connect(username=user,password=passwd)
        sftp = paramiko.SFTPClient.from_transport(transport)
        # local = '/root/test.py'
        # dir2 = 'C:/Users/wuxk/jaina-home/main/test.py'
        sftp.get(file,toFile)
        sftp.close()

        return '200'
    elif cmd == 'sftpUpload':
        # 传入IP、用户名、下载的文件路径、下载到的路径
        ip = flask.request.values.get('ip')
        user = flask.request.values.get('user')
        file = flask.request.values.get('file')
        toFile = flask.request.values.get('toFile')
        name = flask.request.values.get('name')
        passwd,port = iuGetpp(ip,user,name)

        transport = paramiko.Transport((ip,int(port)))
        transport.connect(username=user,password=passwd)
        sftp = paramiko.SFTPClient.from_transport(transport)

        sftp.put(file,toFile)
        sftp.close()

        return '200'
    elif cmd == 'sftpLinuxSize':
        # 传入IP、用户名、下载的文件路径、下载到的路径
        ip = flask.request.values.get('ip')
        user = flask.request.values.get('user')
        toFile = flask.request.values.get('toFile')
        name = flask.request.values.get('name')
        passwd,port = iuGetpp(ip,user,name)

        transport = paramiko.Transport((ip,int(port)))
        transport.connect(username=user,password=passwd)
        sftp = paramiko.SFTPClient.from_transport(transport)

        fileSize = sftp.stat(toFile).__str__().split()[4]
        sftp.close()

        return fileSize
    elif cmd == 'sftpWindowsSize':
        file = flask.request.values.get('file')
        fileSize = os.path.getsize(file.__str__()).__str__()

        return fileSize
    elif cmd == 'startMonitor':
        # 执行一条命令
        monitor = flask.request.values.get('monitor')
        ip = flask.request.values.get('ip')
        user = flask.request.values.get('user')
        name = flask.request.values.get('name')

        passwd,port = iuGetpp(ip,user,name)

        ssh = paramiko.SSHClient();
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
        ssh.connect(ip,port,user,passwd,timeout=12)
        stdin, stdout, stderr = ssh.exec_command(monitor)
        result = stdout.read()
        return result

    return "200"

if __name__ == '__main__':
    try:
        api.run(port=1111, debug=False, host='127.0.0.1')
    except Exception as e:
        logger.error(e)